package bud.taskmanager.user.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import bud.taskmanager.user.dto.User;

@Repository(value = "UserDao")
public class UserDao {

	@Autowired
	private SimpleJdbcTemplate template;

	public void createUser(User user) {
		template.update(
				"INSERT INTO USERS (LOGIN, PSWD, FIRSTNAME, LASTNAME, MAIL, CREATED_ON) VALUES (:login, SHA1(:pswd), :firstname, :lastname, :mail, CURRENT_TIMESTAMP)",
				new BeanPropertySqlParameterSource(user));
	}

	public List<User> findAllUsers() {
		return template
				.query("SELECT ID, LOGIN, FIRSTNAME, LASTNAME, MAIL, STATUS, LAST_LOGIN_ON, CREATED_ON FROM USERS ORDER BY CREATED_ON ASC",
						new BeanPropertyRowMapper<User>(User.class));
	}

	public void deleteUser(int id) {
		template.update("DELETE FROM USERS WHERE ID=?", id);
	}

	public User findUser(int id) {
		return template
				.queryForObject(
						"SELECT ID, LOGIN, FIRSTNAME, LASTNAME, MAIL, STATUS, LAST_LOGIN_ON, CREATED_ON FROM USERS WHERE ID=?",
						new BeanPropertyRowMapper<User>(User.class), id);
	}

	public void updateUSer(User user) {
		template.update(
				"UPDATE USERS SET LOGIN=:login, FIRSTNAME=:firstname, LASTNAME=:lastname, MAIL=:mail, PSWD=SHA1(:pswd), UPDATED_ON=CURRENT_TIMESTAMP WHERE ID=:id",
				new BeanPropertySqlParameterSource(user));
	}

}
